package com.swm.yzgrtk.utils;

import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * @author 师文明
 * @data 2025/1/15 下午4:08
 **/
public class DataTransUtil {
    /**
     * 数组转换成十六进制字符串
     * @param
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    // ASCII to Hex
    public static String asciiToHex(String asciiString) {
        StringBuilder hexBuilder = new StringBuilder();
        for (byte b : asciiString.getBytes(StandardCharsets.US_ASCII)) {
            hexBuilder.append(String.format(Locale.getDefault(), "%02X", b));
        }
        return hexBuilder.toString();
    }

    // Hex to ASCII
    public static String hexToAscii(String hexString) {
        if (hexString.length() % 2 != 0) {
            DialogUtil.showDialog("已经是ASCII");
            throw new IllegalArgumentException("Hex string must have even number of characters");

        }
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hexString.substring(i * 2, i * 2 + 2), 16);
        }
        return new String(bytes, StandardCharsets.US_ASCII);
    }
}
